<!--查看实施轨迹-->
<template>
  <div class="trackContainer">
    <van-sticky>
      <!--头部bar开始-->
      <CommonBar :options="options"></CommonBar>
      <!--头部bar结束-->
    </van-sticky>
    <p class="bottomcount bottomradius bottomcountfix" @click="topela" v-show="toptitleshow">查询历史轨迹</p>
    <div class="formdiv searchdiv fadeleftdown" v-show="topellipsis">
      <!--请假表单开始-->
      <van-cell-group>
        <!--日期-->
        <van-field
          required
          readonly
          clickable
          label="日期"
          :value="signdate"
          placeholder="请选择"
          @click="showPickerdate = true"
          right-icon="arrow"
          type="datetime"
        />
        <van-popup v-model="showPickerdate" position="bottom">
          <van-datetime-picker
            type="date"
            @cancel="showPickerdate = false"
            @confirm="onConfirmdate"
            v-model="currentDate1"
            :min-date="minDate"
            :max-date="maxDate"
            :formatter="formatter"
          />
        </van-popup>
        <!-- 开始时间-->
        <!-- 开始时间-->
        <van-field
          required
          readonly
          clickable
          label="开始时间"
          :value="start_date"
          placeholder="请选择"
          @click="showPickerstart = true"
          right-icon="arrow"
          type="datetime"
        />
        <van-popup v-model="showPickerstart" position="bottom">
          <van-datetime-picker
            type="time"
            @cancel="showPickerstart = false"
            @confirm="onConfirmstart_date"
            v-model="currentDate"
            :formatter="formatter"
          />
        </van-popup>
        <!-- 结束时间-->
        <van-field
          required
          readonly
          clickable
          label="结束时间"
          :value="end_date"
          @click="showPickerend = true"
          placeholder="请选择"
          right-icon="arrow"
          type="datetime"
        />
        <van-popup v-model="showPickerend" position="bottom">
          <van-datetime-picker
            type="time"
            @cancel="showPickerend = false"
            @confirm="onConfirmend_date"
            v-model="currentDate"
            :formatter="formatter"
          />
        </van-popup>
      </van-cell-group>
      <div class="butbottom">
        <button class="subbut" @click="submitdata">确定</button>
      </div>
      <p class="bottomcount bottomradius" @click="topelatitle">查询历史轨迹</p>
    </div>
    <!--地图开始-->
    <div class="mapclass">
      <div id="bmap" class="bm-view"></div>
    </div>
    <!--地图结束-->
  </div>
</template>
<script>
import BMap from "BMap";
import CommonBar from "../common/commonBar";
import { mapState } from "vuex";
export default {
  components: {
    CommonBar
  },
  computed: {
    ...mapState({
      token: state => state.Authorization
    })
  },
  mounted() {
    this.initBmap();
  },
  data() {
    return {
      options: {
        type: "icon",
        centerText: "历史轨迹",
        iconNname: "wap-home",
        lefttype: "left"
      },
      start_date: "", //开始时间
      end_date: "", //结束时间
      showPickerend: false,
      showPickerstart: false,
      showPickerdate: false,
      currentDate: "00:00",
      signdate: "", //出生日期
      currentDate1: new Date(),
      minDate: new Date(2019, 1, 1),
      maxDate: new Date(),
      bmap: null,
      detailId: "",
      detailType: "",
      detailLng: "",
      detailLat: "",
      curday: "",
      starttime: "",
      endtime: "",
      startms: "",
      endms: "",
      historyPoints: [],
      historyLayer: null,
      historyMarker: null,
      pointPlayIndex: 0,
      historyPlaySpeed: 1000,
      hbmap_path: null,
      toptitleshow: false,
      topellipsis: true,
      icon_map: {
        user: require("../../../static/image/mapuser.png"),
        car: require("../../../static/image/car-online.png"),
        manager: require("../../../static/image/manager-offline.png")
      },
      markerpoint: "",
      originalData: [], // 存放历史轨迹的原始数据
      translateCallback: "",
      points_result: [],
      apoint: []
    };
  },
  created() {
    this.showDate();
    this.detailId = this.$route.query.id;
    this.detailType = this.$route.query.type;
    this.detailLng = this.$route.query.lng;
    this.detailLat = this.$route.query.lat;
    this.start_date = "00:00";
    this.end_date = "23:59";
    this.starttime = this.signdate + " " + this.start_date;
    this.endtime = this.signdate + " " + this.end_date;
    this.startms = new Date(this.starttime.replace(/-/g, "/")).getTime();
    this.endms = new Date(this.endtime.replace(/-/g, "/")).getTime();
    console.log(
      this.detailId,
      this.detailType,
      this.detailLng,
      this.detailLat,
      this.startms,
      this.endms
    );
  },
  methods: {
    topela() {
      this.topellipsis = !this.topellipsis;
      this.toptitleshow = !this.toptitleshow;
    },
    topelatitle() {
      this.topellipsis = !this.topellipsis;
      this.toptitleshow = !this.toptitleshow;
    },
    /**地图操作 */
    initBmap() {
      var icon = new BMap.Icon(
        this.icon_map[this.detailType],
        new BMap.Size(31, 35),
        { anchor: new BMap.Size(15, 35) }
      );
      this.bmap = new BMap.Map("bmap", { drawer: BMAP_SVG_DRAWER });
      var point = new BMap.Point(this.detailLng, this.detailLat);
      this.markerpoint = new BMap.Marker(point, { icon: icon }); // 创建标注
      this.bmap.addOverlay(this.markerpoint); // 将标注添加到地图中
      // marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
      this.bmap.centerAndZoom(point, 13);
      this.bmap.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
      this.bmap.setDefaultCursor("pointer");
    },
    //日期选中
    onConfirmdate(val) {
      var d = new Date(val);
      let year = val.getFullYear();
      let month = val.getMonth() + 1;
      let day = val.getDate();
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }
      var datetime = year + "-" + month + "-" + day;
      this.signdate = datetime;
      this.showPickerdate = false;
    },
    //开始时间和结束时间
    onConfirmTime() {
      var date = new Date();
      var year = date.getFullYear();
      var month = date.getMonth();
      var day = date.getDate();
      this.minDate = new Date(year - 1, month, day);
      this.maxDate = new Date(year + 1, month, day);
    },
    formatter(type, value) {
      if (type === "year") {
        return `${value}年`;
      } else if (type === "month") {
        return `${value}月`;
      } else if (type === "day") {
        return `${value}日`;
      } else if (type === "hour") {
        return `${value}时`;
      } else if (type === "minute") {
        return `${value}分`;
      }
      return value;
    },

    //开始时间
    onConfirmstart_date(val) {
      this.start_date = val;
      this.starttime = this.signdate + " " + this.start_date;
      console.log(this.starttime);
      this.startms = new Date(this.starttime.replace(/-/g, "/")).getTime();
      console.log(this.startms);
      this.showPickerstart = false;
    },

    //结束时间
    onConfirmend_date(val) {
      this.end_date = val;
      this.endtime = this.signdate + " " + this.end_date;
      console.log(this.endtime);
      this.showPickerend = false;
      this.endms = new Date(this.endtime.replace(/-/g, "/")).getTime();
      console.log(this.endms);
      if (
        new Date(this.starttime.replace(/-/g, "/")) >
        new Date(this.endtime.replace(/-/g, "/"))
      ) {
        this.$toast({ message: "结束时间不能大于开始时间,请重新选择" });
        this.showPickerend = false;
        this.end_date = "";
      }
    },
    //当前时间
    //当前日期
    showDate() {
      var d = new Date();
      let year = d.getFullYear();
      let month = d.getMonth() + 1;
      let day = d.getDate();
      let hour = d.getHours();
      let minute = d.getMinutes();
      if (month >= 1 && month <= 9) {
        month = `0${month}`;
      }
      if (day >= 1 && day <= 9) {
        day = `0${day}`;
      }
      if (hour >= 0 && hour <= 9) {
        hour = `0${hour}`;
      }
      if (minute >= 0 && minute <= 9) {
        minute = `0${minute}`;
      }
      this.signdate = `${year}-${month}-${day}`; //当天日期
    },
    //提交信息开始
    submitdata() {
      window.clearTimeout(this.timeinter);
      this.historyPoints = [];
      this.historyLayer = null;
      this.bmap.clearOverlays();
      if (this.start_date.length == 0) {
        this.$toast({ message: "请选择开始时间" });
        return false;
      }
      if (this.end_date.length == 0) {
        this.$toast({ message: "请选择结束时间" });
        return false;
      }
      this.markerpoint.hide();
      this.topellipsis = !this.topellipsis;
      this.toptitleshow = !this.toptitleshow;
      //车辆轨迹
      if (this.detailType == "car") {
        var params = {
          token: this.token,
          id: this.detailId,
          date: this.signdate,
          start_time: this.startms,
          end_time: this.endms
        };
        this.$http
          .get(
            `${this.$basePath}?service=App.GetUserOrCar.GetCarTrajectory&api=93`,
            {
              params: params
            }
          )
          .then(res => {
            if (res.ret == 200) {
              console.log("车辆轨迹", res.data[params.id]);
              if (res.data[params.id].length > 0) {
                this.originalData = res.data[params.id].reverse();
                console.log("原始数据", this.originalData);
                this.playHistory(res.data[params.id], 0);
              } else {
                // this.markerpoint.show();
                this.initBmap();
                this.$toast({ message: "没有符合条件的数据" });
              }
            } else {
              this.$toast({ message: res.msg });
            }
          });
      } else if (this.detailType == "user") {
        var params = {
          token: this.token,
          id: this.detailId,
          date: this.signdate,
          start_time: this.startms,
          end_time: this.endms
        };
        this.$http
          .get(
            `${this.$basePath}?service=App.GetUserOrCar.GetUserTrajectory&api=93`,
            {
              params: params
            }
          )
          .then(res => {
            if (res.ret == 200) {
              console.log("人员轨迹", res.data[params.id]);
              if (res.data[params.id].length > 0) {
                this.playHistory(res.data[params.id], 0);
              } else {
                this.initBmap();
                // this.markerpoint.show();
                this.$toast({ message: "没有符合条件的数据" });
              }
            } else {
              this.$toast({ message: res.msg });
            }
          });
      } else if (this.detailType == "manager") {
        var params = {
          token: this.token,
          id: this.detailId,
          date: this.signdate,
          start_time: this.startms,
          end_time: this.endms
        };
        this.$http
          .get(
            `${this.$basePath}?service=App.GetUserOrCar.GetSystemTrajectory&api=93`,
            {
              params: params
            }
          )
          .then(res => {
            if (res.ret == 200) {
              console.log("管理员轨迹", res.data[params.id]);
              if (res.data[params.id].length > 0) {
                this.playHistory(res.data[params.id], 0);
              } else {
                this.initBmap();
                // this.markerpoint.show();
                this.$toast({ message: "没有符合条件的数据" });
              }
            } else {
              this.$toast({ message: res.msg });
            }
          });
      }
    },
    //播放历史轨迹
    /**筛选条件 */
    // 时间戳转年月日时分秒
    add0(m) {
      return m < 10 ? "0" + m : m;
    },
    timeFormat(ts) {
      var that = this;
      var result = "";
      if (typeof ts === "number") {
        switch (ts.toString().length) {
          case 10:
            ts = ts * 1000;
            var time = new Date(ts);
            var y = time.getFullYear();
            var m = time.getMonth() + 1;
            var d = time.getDate();
            var h = time.getHours();
            var mm = time.getMinutes();
            var s = time.getSeconds();
            return (
              y +
              "-" +
              that.add0(m) +
              "-" +
              that.add0(d) +
              " " +
              that.add0(h) +
              ":" +
              that.add0(mm) +
              ":" +
              that.add0(s)
            );
          case 13:
            var time = new Date(ts);
            var y = time.getFullYear();
            var m = time.getMonth() + 1;
            var d = time.getDate();
            var h = time.getHours();
            var mm = time.getMinutes();
            var s = time.getSeconds();
            return (
              y +
              "-" +
              that.add0(m) +
              "-" +
              that.add0(d) +
              " " +
              that.add0(h) +
              ":" +
              that.add0(mm) +
              ":" +
              that.add0(s)
            );
            break;
        }
      }
    },
    playHistory(points, index) {
      if (!this.hbmap_path) {
        console.info("重新转化坐标并绘制历史轨迹");
        this.wgs84ToBd09();
      }
     
    },
    // 原始坐标转百度坐标
    wgs84ToBd09() {
      var that = this;
      var coordtransform = require("coordtransform");
      var originalData = that.originalData;
      for (let i in originalData) {
        var point_GCj02 = coordtransform.wgs84togcj02(
          originalData[i].longitude,
          originalData[i].latitude
        );

        var point_BD09 = coordtransform.gcj02tobd09(
          point_GCj02[0],
          point_GCj02[1]
        );
        originalData[i].longitude = point_BD09[0];
        originalData[i].latitude = point_BD09[1];
        var point = new BMap.Point(point_BD09[0], point_BD09[1]);

        that.points_result.push(point);
      }
      console.info("转换后的坐标", that.points_result);

      var style_polyline = {
        strokeColor: "#700090", //边线颜色。
        strokeWeight: 4, //边线的宽度，以像素为单位
        strokeOpacity: 0.8, //边线透明度，取值范围0 - 1
        fillOpacity: 0.3, //填充的透明度，取值范围0 - 1
        strokeStyle: "solid" //边线的样式，solid或dashed
      };
      var polyline = new BMap.Polyline(that.points_result, style_polyline);
      this.hbmap_path = polyline;
      this.bmap.addOverlay(polyline);
      this.bmap.setViewport(polyline.getPath());
    }
    //坐标转换
  },
  beforeDestroy() {
    console.log(111);
    window.clearTimeout(this.timeinter);
  }
};
</script>
<style lang="less" scoped>
.bm-view {
  width: 100%;
  height: 100vh;
}
.butbottom {
  width: 100%;
  padding: 10px 0;
  background: #fff;

  .subbut {
    width: 92%;
    height: 40px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 12px;
    color: #fff;
    background: rgba(10, 213, 145, 1);
    border-radius: 5px;
    margin: 0 auto;
    outline: none;
    border: none;
  }
}
/deep/ .van-field__control {
  text-align: right;
}
.bottomcountfix {
  position: fixed;
  top: 46px;
  left: 50%;
  -webkit-transform: translate(-50%, 0);
  transform: translate(-50%, 0);
  z-index: 9;
}
.bottomradius {
  border-radius: 0 0 5px 5px !important;
}
.bottomcount {
  font-size: 12px;
  border-radius: 0 5px 5px 0;
  color: #fff;
  background-color: #f58914;
  width: 80px;
  text-align: center;
  padding: 5px 8px;
  margin: 0 auto;
  border-radius: 5px 5px 0 0;
}
.searchdiv {
  position: fixed;
  top: 46px;
  z-index: 9;
  left: 0;
  width: 100%;
}
/**从上往下 */
.fadeleftdown {
  -webkit-animation: fadeleftdown 1s;
  animation: fadeleftdown 1s;
}
@keyframes fadeleftdown {
  0% {
    -webkit-transform: translate3d(0, -20%, 0);
    -webkit-transform: translate3d(0, -20%, 0);
    transform: translate3d(0, -20%, 0);
    transform: translate3d(0, -20%, 0);
    opacity: 0;
  }
  100% {
    -webkit-transform: none;
    transform: none;
    opacity: 1;
  }
}
/deep/ .van-picker__cancel,
/deep/ .van-picker__confirm {
  color: #0ad691;
}
</style>